package net.yxsoft.kit;

import com.jfinal.kit.HttpKit;
import net.sf.json.JSONObject;


import org.apache.commons.lang.StringUtils;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class ShebaoKit   {

    private static String sha256Platform(JSONObject jObj, String secretKey){
        try{
            StringBuffer stringSignTemp = new StringBuffer();
            stringSignTemp.append(jObj.getString("platformId"));
            stringSignTemp.append(jObj.getString("platformSeqId"));
            stringSignTemp.append(jObj.getString("platformTransDate"));
            stringSignTemp.append(jObj.getString("platformTransTime"));
            stringSignTemp.append(jObj.getString("transCode"));
            stringSignTemp.append(secretKey);
            stringSignTemp.append(jObj.getString("dataString"));
            System.out.println("stringSignTemp:"+stringSignTemp);
            MessageDigest sha1 = MessageDigest.getInstance("SHA-256");
            sha1.update(stringSignTemp.toString().getBytes("utf-8"));
            byte[] sha1Bytes = sha1.digest();

            String sign = bin2hex(sha1Bytes);

            return sign;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static String getRequestParamString(Map<String, String> requestParam, String coder) {
        if (null == coder || "".equals(coder)) {
            coder = "UTF-8";
        }
        StringBuffer sf = new StringBuffer("");
        String reqstr = "";
        if (null != requestParam && 0 != requestParam.size()) {
            for (Map.Entry<String, String> en : requestParam.entrySet()) {
                try {
                    sf.append(en.getKey()
                            + "="
                            + (null == en.getValue() || "".equals(en.getValue()) ? "" : URLEncoder
                            .encode(en.getValue(), coder)) + "&");
                } catch (UnsupportedEncodingException e) {
                    System.out.println("不支持的编码异常:"+e.toString());
                    return "";
                }
            }
            reqstr = sf.substring(0, sf.length() - 1);
        }
        return reqstr;
    }

    public static void prepareHeadInfo(JSONObject jObj, String platformId)
    {
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        jObj.put("platformId", platformId);//"testId14");
        jObj.put("platformTransDate", time.substring(0, 8));
        jObj.put("platformTransTime", time.substring(8, 14));
    }




    public static void validatorHelper(JSONObject jObj, String platformSecret) throws Exception{
        jObj.put("encType", "SM4");
        jObj.put("signType", "SM2");
        jObj.put("version", "1.0.0");

        StringBuilder sb = new StringBuilder();
        String encData = null;
        if (jObj.containsKey("data")){
            String data = jObj.getString("data");
            System.out.println("加密前：" + data);
            sb.append("data=").append(data).append("&");
            encData = SM234Util.sm4Encrypt(platformSecret.substring(0, 16), data);
            System.out.println("加密后：" + encData);
        }
        sb.append("encType=").append("SM4").append("&platformId=").append(jObj.getString("platformId"))
                .append("&platformSeqId=").append(jObj.getString("platformSeqId")).append("&platformTransDate=").append(jObj.getString("platformTransDate")).append("&platformTransTime=").append(jObj.getString("platformTransTime"))
                .append("&signType=").append("SM3").append("&transCode=").append(jObj.getString("transCode")).append("&version=").append("1.0.0").append("&key=").append(platformSecret);

        String plainText = sb.toString();
        System.out.println("待签名字符串：" + plainText);
        String sign = SM234Util.sm3Sign(platformSecret, plainText);
        System.out.println("签名：" + sign);
        jObj.put("signData", sign);

        if (!StringUtils.isBlank(encData)){
            jObj.remove("data");
            jObj.put("encData", encData);
        }
    }

    public static String jsonRequest(String msg, String url) throws Exception{
        System.out.println("请求地址：" + url);
        System.out.println("请求报文：" + msg);
        Map<String,String> headers=new HashMap<String,String>(16);
        headers.put("Content-Type","application/json");
        String result= HttpKit.post(url,null, msg.toString(),headers);
        System.out.println("返回结果：" + result);
        return result;
    }

    public static String rtValidate(String result, String platformSecret) throws Exception{
        JSONObject jObj = JSONObject.fromObject(result);
        String signData = jObj.getString("signData");
        if (StringUtils.isBlank(signData)){
            return signData;
        }
        StringBuilder sb = new StringBuilder();
        String data = null;
        if (jObj.containsKey("encData")){
            String encData = jObj.getString("encData");
            System.out.println("加密参数：" + encData);
            data = SM234Util.sm4Decrypt(platformSecret.substring(0, 16), encData);
            sb.append("data=").append(data).append("&");
            System.out.println("解密后：" + data);
        }
        sb.append("encType=").append("SM4").append("&rtCode=").append(jObj.getString("rtCode"))
                .append("&rtMsg=").append(jObj.getString("rtMsg")).append("&signType=").append("SM3")
                .append("&key=").append(platformSecret);

        String plainText = sb.toString();
        System.out.println("待签名字符串：" + plainText);
        String sign = SM234Util.sm3Sign(platformSecret, plainText);
        System.out.println("处理后签名：" + sign);
        System.out.println("返回的签名：" + signData);
        if(signData.equals(sign)) {
            return  data;
        }else {
            return  data;
        }
    }


    public static String bin2hex(byte[] bin)
    {
        char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        StringBuilder sb = new StringBuilder();
        for (int i = 0 ; i < bin.length; i++)
        {
            char upper = hex[(bin[i] & 0xf0) >>> 4];
            char lower = hex[(bin[i] & 0x0f)];
            sb = sb.append(upper).append(lower);
        }
        return sb.toString();
    }





}
